import axios, {type AxiosResponse} from "axios";
import {SERVICE_BASE_URL} from "@/configs";
import type {ResponseData} from "@/services/common/type";
import {APIError} from "@/services/common/common";
import type {AxiosInstanceWithAPI} from "@/services/http/type";

const http: AxiosInstanceWithAPI = axios.create({
  baseURL: SERVICE_BASE_URL,
  timeout: 30000
})

http.interceptors.request.use((config) => {
  Object.assign(config.headers, {"access-key": import.meta.env.VITE_ACCESS_KEY})
  return config
})

http.interceptors.response.use((response: AxiosResponse<ResponseData>) => {
  const {data, errCode, errMsg} = response.data
  if (errCode!==0) throw new APIError(errMsg)
  return data
})

export default http